﻿namespace Sage.Caching.Memory.Models
{
    /// <summary>
    /// 缓存统计信息类，用于跟踪缓存的命中次数、未命中次数、总项数和总大小。
    /// </summary>
    public class CacheStats
    {
        // 使用字段而不是属性，以便可以用于 ref 参数
        internal long _hits;
        internal long _misses;
        internal long _totalItems;
        internal long _totalSize;
        internal long _addedItems;
        internal long _removedItems;
        internal long _evictedItems;

        /// <summary>
        /// 缓存命中次数。
        /// </summary>
        public long Hits => _hits;

        /// <summary>
        /// 缓存未命中次数。
        /// </summary>
        public long Misses => _misses;

        /// <summary>
        /// 缓存项总数。
        /// </summary>
        public long TotalItems => _totalItems;

        /// <summary>
        /// 缓存占用的总内存大小估计（单位：字节）。
        /// </summary>
        public long TotalSize => _totalSize;

        /// <summary>
        /// 获取缓存命中率。
        /// </summary>
        public double HitRate => Hits + Misses == 0 ? 0 : (double)Hits / (Hits + Misses);

        /// <summary>
        /// 最近一次统计数据刷新的时间。
        /// </summary>
        public DateTime LastUpdated { get; internal set; } = DateTime.UtcNow;

        /// <summary>
        /// 添加到缓存的项目计数。
        /// </summary>
        public long AddedItems => _addedItems;

        /// <summary>
        /// 从缓存中删除的项计数。
        /// </summary>
        public long RemovedItems => _removedItems;

        /// <summary>
        /// 由于内存压力而被逐出的项计数。
        /// </summary>
        public long EvictedItems => _evictedItems;

        /// <summary>
        /// 创建一个新的 CacheStats 实例的快照。
        /// </summary>
        /// <returns>当前统计信息的快照。</returns>
        public CacheStats CreateSnapshot()
        {
            var snapshot = new CacheStats
            {
                _hits = _hits,
                _misses = _misses,
                _totalItems = _totalItems,
                _totalSize = _totalSize,
                _addedItems = _addedItems,
                _removedItems = _removedItems,
                _evictedItems = _evictedItems,
                LastUpdated = DateTime.UtcNow
            };
            return snapshot;
        }
    }
}
